package burubaka.controller.mnt;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.apache.commons.lang3.StringUtils;
import org.slim3.controller.Navigation;
import org.slim3.controller.upload.FileItem;

import burubaka.BurubakaConstants;
import burubaka.common.controller.Controller;
import burubaka.model.PreRaceInfo;
import burubaka.service.PreRaceInfoService;

/**
 * @author tk
 * 
 */
public class PreRaceInfoController extends Controller {

	private static final Logger log = Logger.getLogger(PreRaceInfoController.class.getName());

	private static final String PRE_RACE_INFO_JSP = "preRaceInfo.jsp";

	private PreRaceInfoService preRaceInfoService = new PreRaceInfoService();

	@Override
	public Navigation init() throws Exception {
		return forward(PRE_RACE_INFO_JSP);
	}

	/**
	 * 登録
	 * 
	 * @return Navigation
	 * @throws Exception
	 */
	public Navigation regist() throws Exception {

		FileItem preRaceFile = requestScope("preRaceFile");
		if (preRaceFile == null) {
			requestScope(BurubakaConstants.RESPONSEKEY_ERROR, "ファイルがない");
			return forward(PRE_RACE_INFO_JSP);
		}
		InputStream is = new ByteArrayInputStream(preRaceFile.getData());

		BufferedReader reader = new BufferedReader(new InputStreamReader(is, BurubakaConstants.ENCODE_SJIS));

		List<PreRaceInfo> preRaceInfoList = new ArrayList<PreRaceInfo>();
		String line = null;
		while ((line = reader.readLine()) != null) {
			String[] array = line.split(",");
			PreRaceInfo pre = new PreRaceInfo();
			pre.setRaceDate(array[0]);
			pre.setRaceName(array[1]);
			String dispRaceName = array[2];
			if (StringUtils.isEmpty(array[2])) {
				dispRaceName = array[1];
			}
			pre.setDisplayRaceName(dispRaceName);
			pre.setDistrictClass(array[3]);
			pre.setExecFlag(Integer.parseInt(array[4]));
			preRaceInfoList.add(pre);
		}

		preRaceInfoService.regist(preRaceInfoList);

		return forward(PRE_RACE_INFO_JSP);
	}
}
